#include <iostream>
#include <memory>
#include "TcpServer.hpp"
#include "Protocol.hpp"
#include "Calculator.hpp"
#include "Factory.hpp"
using namespace std;

string ServerHandler(string &message, Protocol pro)
{
    unique_ptr<Factory> ft(new Factory());
    string content;
    // 1. 解包并截取收到的完整报文
    if (pro.Unpacking(message, &content)) 
    {
        // cout << "请求有效载荷: " << content << endl;

        // 2. 请求报文的有效载荷反序列化
        shared_ptr<Calculator::Request> req = ft->BuildRequest();
        bool ok;
        req->Deserialize(content, &ok);
        if (!ok)
            return "";

        // 3. 处理有效载荷
        // req->Debug();
        shared_ptr<Calculator::Response> res = req->Result();
        // cout << "结果：";
        // res->Debug();
        //  5. 结果序列化
        res->Serialize(&content);
        // 6. 封装响应报文
        string msg;
        pro.Package(content, &msg);
        // cout << "响应报文：" << msg << endl;
        return msg;
    }
    else
    {
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cout << "Incorrect use: " << endl
             << "    " << argv[0] << " port" << endl;
        return 1;
    }

    uint16_t port = stoi(argv[1]);

    unique_ptr<TcpServer> up(new TcpServer(port, bind(&ServerHandler, placeholders::_1, Protocol())));

    up->Loop();
    return 0;
}